/**
 * 
 */
package io.potato.core.util;

import java.util.ArrayList;
import java.util.List;

/**
 * 列表分页
 * @author timl
 * created: 2019年2月12日 下午4:28:17
 */
public class PagedList<T> {
	
	/**
	 * 列表
	 */
	private List<T> list = null;
	
	/**
	 * 每页大小
	 */
	private int pageSize;
	
	/**
	 * 总页数
	 */
	private int totalPage;
	
	/**
	 * 列表元素总个数
	 */
	private int size;
	
	public PagedList(List<T> list, int pageSize) {
		
		if (pageSize <= 0) {
			throw new IllegalArgumentException("pageSize");
		}
		
		if (list == null || list.isEmpty()) {
			return;
		}
		
		this.list = list;
		this.pageSize = pageSize;
		
		size = list.size();
		
		// 计算有多少页
		if (size % this.pageSize == 0) {
			totalPage = size / this.pageSize;
		} else {
			totalPage = size / this.pageSize + 1;
		}
	}
	
	/**
	 * 返回指定页数的数据
	 * @param index 第几页，从0开始
	 * @return
	 */
	public List<T> getPage(int index) {
		
		if (list == null) {
			return null;
		}
		
		if (index < 0 || index >= totalPage) {
			throw new IndexOutOfBoundsException("index");
		}
		
		int fromIndex = index * pageSize;
		int toIndex = fromIndex + pageSize;
		if (toIndex > size) {
			toIndex = size;
		}
		
		return list.subList(fromIndex, toIndex);
	}
	
	/**
	 * 返回总页数
	 * @return 总页数
	 */
	public int getTotalPage() {
		return totalPage;
	}
	
	
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();
		for (int i = 1; i <= 10; i++) 
			list.add(i);
		
		PagedList<Integer> pagedList = new PagedList<>(list, 8);
		
		for (int j = 0; j < pagedList.getTotalPage(); j++) {
			System.out.println(pagedList.getPage(j));
		}
	}
	
}
